package com.xinxing.city.recoverycheck.sdk_ttys;

import android.util.Log;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Hexs {

    public static final Charset DEFAULT_CHARSET;
    public static final String DEFAULT_CHARSET_NAME = "UTF-8";
    private static final char[] DIGITS_LOWER;
    private static final char[] DIGITS_UPPER;

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
        DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        DIGITS_UPPER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    }

    public static String FormatZeroLeft(String str, int length) {
        if (str != null) str = str.trim();
        return String.format("%" + (length * 2) + "s", str).replace(" ", "0");//不足2位补零
    }
    /**
     * 截取byte数组   不改变原数组
     * @param src 原数组
     * @param srcPos 偏差值（索引）
     * @param length 长度
     * @return 截取后的数组
     */
    public static byte[] subByte(byte[] src, int srcPos, int length){

        if(src.length<1)return new byte[0];
        if(length<1)return new byte[0];

        if(src.length<(length+srcPos))
        {
            throw new ArrayIndexOutOfBoundsException("原数组长度不够 ");
        }

        byte[] dest = new byte[length];
        System.arraycopy(src, srcPos, dest, 0, length);
        return dest;
    }
    public static byte[] HexToByte(String hexString)throws Exception {
        return HexToByte(hexString.toCharArray());
    }
    public static byte[] HexToByte(char[] data) throws Exception {
        byte[] out = new byte[data.length >> 1];
        HexToByte(data, out, 0);
        return out;
    }


    public static byte[] HexTobyte(String recvPacket) {

        if (recvPacket == null||recvPacket.length()<1) {
            return null;
        }

        byte[] b3 = new byte[0];
        try {
            b3 = Hexs.HexToByte(recvPacket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b3;
    }



    public static int HexToByte(char[] data, byte[] out, int outOffset) throws Exception {
        int len = data.length;
        if ((len & 1) != 0) {
            throw new Exception("Odd number of characters.");
        } else {
            int outLen = len >> 1;
            if (out.length - outOffset < outLen) {
                throw new Exception("Output array is not large enough to accommodate decoded data.");
            } else {
                int i = outOffset;

                for (int j = 0; j < len; ++i) {
                    int f = toDigit(data[j], j) << 4;
                    ++j;
                    f |= toDigit(data[j], j);
                    ++j;
                    out[i] = (byte) (f & 255);
                }

                return outLen;
            }
        }
    }
    protected static int toDigit(char ch, int index) throws Exception {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
        } else {
            return digit;
        }
    }

    // 解码 ByteToHex
    public static String ByteToHex(byte[] data) {
        if (data == null||data.length<1) {
            return null;
        }

        return new String(encodeHex(data));
    }
    public static byte[] subArrayUsingSystemArraycopy(byte[] original, int offset, int length) {
        // 检查offset和length是否有效
        length = length-25-4;
        Log.e("TTT","offset"+offset +"  length "+length+"  original "+original.length);

        if (offset < 0 || length < 0 || offset + length > original.length-1) {
            throw new IndexOutOfBoundsException();
        }

        // 创建新的数组来保存截取的部分
        byte[] subArray = new byte[length];

        // 使用System.arraycopy()来复制数据
        System.arraycopy(original, offset, subArray, 0, length);

        return subArray;
    }
    public static char[] encodeHex(byte[] data) {
        return encodeHex(data, true);
    }
    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }
    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        encodeHex(data, 0, data.length, toDigits, out, 0);
        return out;
    }
    private static void encodeHex(byte[] data, int dataOffset, int dataLen, char[] toDigits, char[] out, int outOffset) {
        int i = dataOffset;

        for (int var7 = outOffset; i < dataOffset + dataLen; ++i) {
            out[var7++] = toDigits[(240 & data[i]) >>> 4];
            out[var7++] = toDigits[15 & data[i]];
        }

    }

    //低位在前 0100 => 1
    public static int LowBytesToInt2F(byte[] bytes){
        int result = 0;
        if(bytes.length == 2){
            int c = (bytes[1] & 0xff) << 8;
            int d = (bytes[0] & 0xff);
            result =  c | d;
        }
        return result;
    }


    //低位在前 1 => 0100
    public static byte[] LowIntToByte2F(int dd) {
        byte[] b = new byte[2];
        String stringdd = String.format("%08x", dd);
        Long SSAsLong = Long.parseLong(stringdd, 16);
        b[0] = (byte) (SSAsLong & 0xff);
        b[1] = (byte) ((SSAsLong >> 8) & 0xff);
        return b;
    }


    /**使用两个 for 语句 合并byte数组 */

    public static byte[] byteMerger(byte[]... bys ) {

        int l = 0;
        for (byte[] bt : bys) {
            if(bt!=null&&bt.length>0){
                l+=bt.length;
            }
        }
        byte[] bt3 = new byte[l];
        int i = 0;
        for (byte[] bt : bys) {
            if(bt!=null&&bt.length>0){
                for (byte b : bt) {
                    bt3[i] = b;
                    i++;
                }
            }
        }
        return bt3;
    }














}
